package HTTP

import (
	"emb/emb_server/SQL/util"
	"emb/emb_server/logs"
	"net/http"
)

// request : groupId  string , userId string
// respon :	Message string
func deleteGroup(w http.ResponseWriter, r *http.Request) {
	var code = Success
	var info = "success"
	var information interface{}

	defer func() {
		writeResult(w, code, info, information)
	}()

	config(w, r)

	err := r.ParseForm()
	if err != nil {
		code = errParseForm
		logs.Print("From:deleteGroup.ParseForm---", err.Error())
		info = "From:deleteGroup.ParseForm---" + err.Error()
		return
	}

	groupID := r.Form["groupID"]
	userID := r.Form["userID"]

	if userID == nil {
		code = errEmtpyID
		logs.Print("From:alterObjectData.ParseForm:---" + err.Error())
		info = "From:alterObjectData:---objectID输入有误,不全是数字或为空"
		return
	}
	if groupID == nil {
		code = errEmtpyID
		logs.Print("From:deleteGroup.ParseForm:---" + err.Error())
		info = "From:deleteGroup:---objectID输入有误,不全是数字或为空"
		return
	}

	ok, code, info := checkOutId(groupID[0])
	if !ok {
		return
	}

	ok, code, info = checkOutId(userID[0])
	if !ok {
		return
	}

	ok, code, info = isManager(userID[0])
	if !ok {
		return
	}

	ok, code, info = deleteGroupFromDB(groupID[0])
	if !ok {
		return
	}

}

func deleteGroupFromDB(id string) (bool, int, string) {
	info := "success"
	sql := "delete from objects where id = $1"

	if id == "" {
		info = "id is null"
		return false, errEmtpyID, info
	}

	db := util.GetDb()
	stmt, err := db.Prepare(sql)
	defer stmt.Close()
	if err != nil {
		logs.Print("From:deleteGroup.Prepare:---", err.Error())
		info = "From:alterObjectData.Prepare:---" + err.Error()
		return false, errDBExecFailed, info
	}

	_, err = stmt.Exec(id)
	if err != nil {
		logs.Print("From:deleteGroup.Exec:---", err.Error())
		info = "From:alterObjectData.Exec:---" + err.Error()
		return false, errDBExecFailed, info
	}

	return true, Success, info

}

func isManager(id string) (bool, int, string) {

	sql := "select ismanager from users where id =$1"
	db := util.GetDb()
	info := "success"

	stmt, err := db.Prepare(sql)
	if err != nil {
		logs.Print("From:deleteGroup.isGroup.Prepare:---", err.Error())
		info = "From:deleteGroup.isGroup.Prepare:---" + err.Error()
		return false, errDBExecFailed, info
	}
	defer stmt.Close()

	rows, err := stmt.Query(id)
	defer rows.Close()
	var ismanager bool
	if !rows.Next() {
		logs.Print("From:deleteGroup.isGroup.rows.Next:---用户ID有误")
		info = "From:deleteGroup.isGroup.rows.Next:---用户ID有误"
		return false, errDBQueryFailed, info
	}
	err = rows.Scan(&ismanager)

	if !ismanager {
		info = "用户不是管理员"
		return false, errInvalidID, info
	}
	return true, Success, info
}
